<?php
namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Http\Requests\BasicRequest;
use App\Http\Requests\LoginRequest;
use App\Models\ClientUser;
use App\Models\Config;

class UserController extends Controller {
	
	public function login(LoginRequest $request){
		$username = $request->input('username');
		$password = $request->input('password');
		$clientUser = new ClientUser();
		$uid = $clientUser->checkLogin($username,$password,[2,5]);
		$data = login($uid);
		$data->accessToken = $this->getToken();

		return json_success('OK',$data);
	}
	
	public function logout(BasicRequest $request){
		$var = logout();
		return json_return($var,'','已退出登录');
	}

    public function getToken(){
        $ys_accessToken=Config::where(['key'=>'ys_accessToken'])->first();
        //若TOKEN超时
        if(time()*1000>$ys_accessToken->remarks){
            $ch = curl_init();
            $url = 'http://open.ys7.com/api/lapp/token/get';
            $header='Content-Type: application/x-www-form-urlencoded';

            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_HEADER,$header);
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,'appKey=d88cd53478294bde8c8c7ee1e0d0861b&appSecret=4484cf5c7833254945ac6d9ef97ae93b');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            curl_close($ch);
            $return = json_decode($output,true);
            $accessToken = $return['data']['accessToken'];
            $expireTime = $return['data']['expireTime'];

            Config::where(['key'=>'ys_accessToken'])->update(['value'=>$accessToken,'remarks'=>$expireTime]);

        }else{
            $accessToken = $ys_accessToken['value'];
        }
        return $accessToken;
    }
}